﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ClassDAL.Entities;



namespace CodeGenBL.Dto
{
    [DataContract]
    public class ClassModelDto
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public List<AttributeModelDto> Attributes { get; set; }
        [DataMember]
        public int ProjectId { get; set; }

        public void AddAttribute(AttributeModelDto attributeModelDto)
        {
            Attributes.Add(attributeModelDto);
        }

        public List<AttributeModelDto> GetAttributes()
        {
            return Attributes;
        }

        public ClassModelDto GetAllPrimaryKey()
        {
            ClassModelDto newDto=new ClassModelDto();
            newDto.Id = this.Id;
            newDto.Name = this.Name;
            newDto.ProjectId = this.ProjectId;

            List<AttributeModelDto> resultList = Attributes.FindAll(a => a.Pk == true);
            foreach (var item in resultList)
            {
                newDto.AddAttribute(item);
            }

            return newDto;
        }

        public ClassModelDto GetAllSearchable()
        {
            ClassModelDto newDto = new ClassModelDto();
            newDto.Id = this.Id;
            newDto.Name = this.Name;
            newDto.ProjectId = this.ProjectId;

            List<AttributeModelDto> resultList = Attributes.FindAll(a => a.Search == true);
            foreach (var item in resultList)
            {
                newDto.AddAttribute(item);
            }
            return newDto;
        }

        public ClassModelDto GetAllDisplay()
        {
            ClassModelDto newDto = new ClassModelDto();
            newDto.Id = this.Id;
            newDto.Name = this.Name;
            newDto.ProjectId = this.ProjectId;

            List<AttributeModelDto> resultList = Attributes.FindAll(a => a.Display == true);
            foreach (var item in resultList)
            {
                newDto.AddAttribute(item);
            }
            return newDto;
        }

    }

    public static class ClassModelExt
    {
        public static ClassModel TransformToClassModel(this ClassModelDto classModelDto)
        {
            Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
            if(!prov.IsValidIdentifier(classModelDto.Name))
            {
                throw new Exception("Invalid Charecters");
            }
            return new ClassModel
            {
                Id = classModelDto.Id,
                Name = classModelDto.Name,
                Attributes = classModelDto.Attributes.TransformToAttributes(),
                ProjectId = classModelDto.ProjectId
            };
        }
    }
}
